<?php

namespace App\Jobs\Controller;

use App\Common\Libs\ArrayHelper;
use App\Consts\GlobalConst;
use App\Consts\GlobalCounterConst;
use App\Consts\GlobalDynamicConst;
use App\Consts\GlobalTopicConst;
use App\Jobs\BaseJob;
use App\Models\Cache\Cache;
use App\Models\Cache\CacheKey;
use App\Models\FeedDynamic;
use App\Models\IndexDynamic;
use App\Models\SysTargetTopic;
use App\Models\SysTopicTarget;

class NoteJob extends BaseJob
{
    /**
     * 删除话题关联关系
     * @param $msgContent
     * @return bool
     */
    public function delTopicTargetRelation($msgContent)
    {
        $targetId = $msgContent['msgContent']['target_id'];

        $targetTopics = SysTargetTopic::getInstance($targetId)
            ->where('target_id', $targetId)
            ->get();

        // 删除[sys_target_topic_]
        SysTargetTopic::getInstance($targetId)
            ->where('target_id', $targetId)
            ->update(['is_deleted' => GlobalConst::IS_DELETED]);

        $topicIdArr = ArrayHelper::getColumn($targetTopics, 'topic_id');
        foreach ($topicIdArr as $topicId) {
            // 删除[sys_topic_target_]
            $topicTarget = SysTopicTarget::getInstance($topicId)
                ->where(['topic_id' => $topicId, 'target_id' => $targetId])
                ->update(['is_deleted' => GlobalConst::IS_DELETED]);

            // 话题的总内容数total -1
            Cache::getInstance([
                'topic_id' => $topicId
            ])->incrFromArray(CacheKey::COUNTER_TOPIC, GlobalCounterConst::COUNT_TOTAL, GlobalCounterConst::DECREASE);

            // 如果该主体是话题的热门内容，则hot_target -1
            if ($topicTarget->is_top == GlobalTopicConst::IS_TOP) {
                Cache::getInstance([
                    'topic_id' => $topicId
                ])->incrFromArray(CacheKey::COUNTER_TOPIC, GlobalCounterConst::COUNT_HOT_TARGET, GlobalCounterConst::DECREASE);
            }
        }

        return true;
    }

    /**
     * 笔记转为私密
     * @param $msgContent
     * @return bool
     */
    public function noteToSelf($msgContent)
    {
        $noteId = $msgContent['msgContent']['note_id'];
        $userId = $msgContent['msgContent']['user_id'];

        $indexDynamic = IndexDynamic::getModel()
            ->where('target_id', $noteId)
            ->first();
        if (!$indexDynamic) {
            return false;
        }
        $indexDynamic = $indexDynamic->updateFormat(['is_view' => GlobalDynamicConst::IS_NOT_VIEW]);

        // 删除该用户所有粉丝的[user_attention_]记录
        repository()->UserRepository->deleteByUserAttentionIdAndTargetId($userId, $indexDynamic->dynamic_id);

        FeedDynamic::getModel()
            ->where('dynamic_id', $indexDynamic->dynamic_id)
            ->update(['is_view' => GlobalDynamicConst::IS_NOT_VIEW]);

        // 除笔记相关评论消息
        repository()->CommentRepository->deleteByNote($noteId, $userId);

        return true;
    }
}
